package com.zl.service.impl;

import com.zl.dao.*;
import com.zl.domain.Contract;
import com.zl.service.ContractService;
import com.zl.util.Util;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ContractServiceImpl extends BaseServiceImpl<Contract> implements
        ContractService {
    @Autowired
    public ProductDao productDao;
    @Autowired
    public PurposeDao purposeDao;
    @Autowired
    public ProvinceDao provinceDao;
    @Autowired
    public CategoryDao categoryDao;
    @Autowired
    public ContractDao contractDao;


    @Override
    public JSONObject findTypes() {
        return new JSONObject().accumulate("products", productDao.findAll())
                .accumulate("provinces", provinceDao.findAll())
                .accumulate("purposes", purposeDao.findAll())
                .accumulate("categories", categoryDao.findAll());
    }


    @Override
    public int insert(Contract contract) {
        contract.setCid(Util.uuid());
        return contractDao.insert(contract);
    }

    @Override
    public JSONObject analysis(String type, String group, String data) {
        List<Map<String, String>> datas = contractDao.analysis(group, data);
        List categories = new ArrayList<String>(), barData = new ArrayList<Integer>();
        boolean isBar = type.equals("bar");
        JSONObject json = new JSONObject();
        for (Map dataMap : datas) {
            categories.add((String) dataMap.get("name"));
            if (isBar) {
                barData.add(Integer.parseInt(dataMap.get("value") + ""));
            }
        }
        json.accumulate("categories", categories.toArray());
        json.accumulate("data", isBar ? barData.toArray() : datas);
        if (type.equals("map"))
            json.accumulate("money", contractDao.analysis("province", "money"));
        return json;
    }
}
